<?php
	namespace App\Services\Push;

use Wrep\Notificato\Apns\MessageEnvelope;
use Wrep\Notificato\Notificato;
	use App\Contracts\Pusher;

	// 正式环境
	if (config('app.env') == 'production') {
		define('PUSH_PRODUCTION', true);
	}
	!defined('PUSH_PRODUCTION') && define('PUSH_PRODUCTION', false);
	!defined('APP_DIR_PATH') && define('APP_DIR_PATH', app_path());
	class apns_cer_config{
		const FILE_PATH = PUSH_PRODUCTION ? APP_DIR_PATH . '/Services/Push/apns_cer/thishop_apns_dev.pem' : APP_DIR_PATH . '/Services/Push/apns_cer/thishop_apns_dis.pem';
		const PWD = PUSH_PRODUCTION  ? '123456' : '123456';
	}

	class Apans implements Pusher {
		public function push($msg){
			$tmp_msg = json_decode($msg, true);
			$device_token = $tmp_msg['token'];
			$alert_title = $tmp_msg['title'];
			$alert_body = $tmp_msg['body'];

			$data = $tmp_msg['data'];

			// First we get a Notificato instance and tell it what certificate to use as default certificate
			$notificato = new Notificato(apns_cer_config::FILE_PATH, apns_cer_config::PWD);

			$alert = array();
			$alert['title'] = $alert_title;
			$alert['body'] = $alert_body;
			$alert['action-loc-key'] = 'action-loc-key';
			$alert['launch-image'] = 'launch-image';

			$message = $notificato->messageBuilder()
									->setDeviceToken($device_token)
									->setBadge(1)
									->setContentAvailable(true)
									->setAlert($alert)
									->setPayload($data)
									->build();

			// The message is ready, let's send it!
			//  Be aware that this method is blocking and on failure Notificato will retry if necessary
			$messageEnvelope = $notificato->send($message);
			if (MessageEnvelope::STATUS_NOERRORS == $messageEnvelope->getFinalStatus()) {
				return true;
			}
			return false;
		}
	}
